"""
Pytorch Classes and methods for complex-valued neural network.
Modified on Jan. 3, 2021.
@author: Pinjing He hepinjing93@gmail.com.

Ref: Trabelsi C, Bilaniuk O, Zhang Y, et al. Deep Complex Networks. arXiv 2018[J]. arXiv preprint arXiv:1705.09792.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import math
import numpy as np
Any = object()
class _Alias:
    # Class for defining generic aliases for library types.
    def __getitem__(self, typeargs: Any) -> Any: ...

List = _Alias()

class CAdam(optim.Optimizer):
    """
    Modifed Adam for complex-valued optimization
    Modified on Dec. 21, 2020.
    @author: Pinjing He hepinjing93@gmail.com.
    """
    def __init__(self, params, lr=1e-3,  betas=(0.9, 0.999), eps=1e-8, weight_decay=0, amsgrad=False):
        if not 0.0 <= lr:
            raise ValueError("Invalid learning rate: {}".format(lr))
        if not 0.0 <= eps:
            raise ValueError("Invalid epsilon value: {}".format(eps))
        if not 0.0 <= betas[0] < 1.0:
            raise ValueError(
                "Invalid beta parameter at index 0: {}".format(betas[0]))
        if not 0.0 <= betas[1] < 1.0:
            raise ValueError(
                "Invalid beta parameter at index 1: {}".format(betas[1]))
        if not 0.0 <= weight_decay:
            raise ValueError(
                "Invalid weight_decay value: {}".format(weight_decay))
        defaults = dict(lr=lr, betas=betas, eps=eps,
                        weight_decay=weight_decay, amsgrad=amsgrad)
        super(CAdam, self).__init__(params, defaults)
        self.state_track = defaults

    def __setstate__(self, state):
        super(CAdam, self).__setstate__(state)
        for group in self.param_groups:
            group.setdefault('amsgrad', False)
    @torch.no_grad()
    def step(self, closure=None):
        """Performs a single optimization step.

        Arguments:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        """
        loss = None
        if closure is not None:
            with torch.enable_grad():
                loss = closure()

        for group in self.param_groups:
            params_with_grad = []
            grads = []
            exp_avgs = []
            exp_avg_sqs = []
            state_sums = []
            max_exp_avg_sqs = []
            state_steps = []

            for p in group['params']:
                if p.grad is not None:
                    params_with_grad.append(p)
                    if p.grad.is_sparse:
                        raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')
                    grads.append(p.grad)

                    state = self.state[p]
                    # Lazy state initialization
                    if len(state) == 0:
                        state['step'] = 0
                        # Exponential moving average of gradient values
                        state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format)
                        # Exponential moving average of squared gradient values
                        state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format)
                        if group['amsgrad']:
                            # Maintains max of all exp. moving avg. of sq. grad. values
                            state['max_exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format)

                    exp_avgs.append(state['exp_avg'])
                    exp_avg_sqs.append(state['exp_avg_sq'])

                    if group['amsgrad']:
                        max_exp_avg_sqs.append(state['max_exp_avg_sq'])

                    # update the steps for each param group update
                    state['step'] += 1
                    # record the step after step update
                    state_steps.append(state['step'])

            beta1, beta2 = group['betas']
            self.cadam(params_with_grad,
                   grads,
                   exp_avgs,
                   exp_avg_sqs,
                   max_exp_avg_sqs,
                   state_steps,
                   group['amsgrad'],
                   beta1,
                   beta2,
                   group['lr'],
                   group['weight_decay'],
                   group['eps']
                   )
        return loss

    def cadam(
        self,
        params: List[torch.Tensor],
        grads: List[torch.Tensor],
        exp_avgs: List[torch.Tensor],
        exp_avg_sqs: List[torch.Tensor],
        max_exp_avg_sqs: List[torch.Tensor],
        state_steps: List[int],
        amsgrad: bool,
        beta1: float,
        beta2: float,
        lr: float,
        weight_decay: float,
        eps: float
    ):
        for i, param in enumerate(params):
            grad = grads[i]
            exp_avg = exp_avgs[i]
            exp_avg_sq = exp_avg_sqs[i]
            step = state_steps[i]
            if amsgrad:
                max_exp_avg_sq = max_exp_avg_sqs[i]

            bias_correction1 = 1 - beta1 ** step
            bias_correction2 = 1 - beta2 ** step

            if weight_decay != 0:
                grad = grad.add(param, alpha=weight_decay)


            # Decay the first and second moment running average coefficient
            exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
            # exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)

            exp_avg_sq.mul_(beta2)
            exp_avg_sq.add_(grad * grad, alpha= 1 - beta2)

            if amsgrad:
                # Maintains the maximum of all 2nd moment running avg. till now
                torch.maximum(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)
                # Use the max. for normalizing running avg. of gradient
                denom = (max_exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(eps)
            else:
                denom = (torch.abs(exp_avg_sq).sqrt() / math.sqrt(bias_correction2)).add_(eps)
                # denom = 1

            step_size = lr / bias_correction1
            param.add_(exp_avg / denom, alpha = -step_size)
            # param.addcdiv_(exp_avg, denom, value=-step_size)

class CDropout(nn.Module):
    """
    Modifed Dropout for complex-valued optimization
    Modified on Dec. 21, 2020.
    @author: Pinjing He hepinjing93@gmail.com.
    """
    def __init__(self, p=0.5):
        super(CDropout, self).__init__()
        self.p = p

    def forward(self, x):
        if self.training:
            msk = torch.bernoulli(torch.ones(x.shape)*(1-self.p)).to(x.device)
            x = x*msk/(1-self.p)
        else:
            x = x

        return x

class CLinear(nn.Module):
    """
    Modifed linear layer for complex-valued NN.
    Modified on Dec. 21, 2020.
    @author: Pinjing He hepinjing93@gmail.com.
    """
    def __init__(self, in_features, out_features, init_parameter=None, bias=True):
        super(CLinear, self).__init__()
        if init_parameter == None:

            sigma = 2/np.sqrt(in_features)
            w_mag = np.random.rayleigh(
                scale=sigma, size=[in_features, out_features])
            w_ang = np.random.uniform(
                low=-np.pi, high=np.pi, size=w_mag.shape)
            w = w_mag * np.exp(1j*w_ang)
            self.weight = nn.Parameter(torch.from_numpy(w), requires_grad=True)
            b_mag = np.random.rayleigh(
                scale=sigma, size=[1,out_features]
            )
            b_ang = np.random.uniform(low=-np.pi, high=np.pi, size=b_mag.shape)
            self.bias = nn.Parameter(torch.from_numpy(b_mag * np.exp(1j*b_ang)), requires_grad=bias)

            self.use_bias = bias
        else:
            in_features_input, out_features_input = init_parameter.shape
            assert(in_features_input == in_features)
            assert(out_features_input == out_features)
            self.weight = nn.Parameter(init_parameter, requires_grad=True)

    def forward(self, x):
        x = x.squeeze()
        '''
        x.shape = [B,in_features]
        self.weight.shape = [in_features, out_features]
        '''
        x = x[..., np.newaxis]
        x = x*self.weight[np.newaxis, ...]
        ret = torch.sum(x, dim=1, keepdim=False)+self.bias * self.use_bias
        return ret

class CReLu(nn.Module):
    def __init__(self, b):
        super(CReLu, self).__init__()
        self.b = nn.Parameter(torch.Tensor([b]), requires_grad=True)

    def forward(self, x):
        absx = torch.abs(x)
        x[(absx+self.b) < 0] = 0
        ret = x
        return ret

class CTanh(nn.Module):
    def __init__(self, m):
        super(CTanh, self).__init__()
        self.m = nn.Parameter(torch.Tensor([m]), requires_grad=True)

    def forward(self, x):
        # power = x * x.conj()
        # absx = torch.pow(power,0.5)
        absx = torch.abs(x)
        ret = torch.tanh(absx / self.m) * x / absx
        return ret

class CSinh(nn.Module):
    def __init__(self, m):
        super(CSinh, self).__init__()
        self.m = nn.Parameter(torch.Tensor([m]), requires_grad=True)

    def forward(self, x):
        # power = x * x.conj()
        # absx = torch.pow(power,0.5)
        absx = torch.abs(x)
        ret = torch.sinh(absx / self.m) * x / absx
        return ret
